// components/tab_menu/tab_menu.js
var App = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    current:'',
    tabBar: [{
      "pagePath": "/pages/index/index",
      "text": "猫盒",
      "iconPath": "../../images/menu/index.png",
      "selectedIconPath": "../../images/menu/index_chosed.png"
    },
    {
      "pagePath": 'miao',
      "text": "喵趣",
      "iconPath": "../../images/menu/miaoqu.png",
      "selectedIconPath": "../../images/menu/miaoqu_chosed.png"
    },
    {
      "pagePath": 'wan',
      "text": "玩赚",
      "iconPath": "../../images/menu/wanzhuan.png",
      "selectedIconPath": "../../images/menu/wanzhuan_chosed.png"
    },
    {
      "pagePath": "/pages/mine/mine",
      "text": "我的",
      "iconPath": "../../images/menu/mine.png",
      "selectedIconPath": "../../images/menu/mine_chosed.png"
    }],
  },
  ready:function(){
    var curPageArr = getCurrentPages();
    var route = curPageArr[curPageArr.length - 1].route;
    this.setData({
      current: '/' + route,
    })

    if (route.indexOf('index/mall/mall') > -1){
      this.setData({
        ['tabBar[0].pagePath']: '/' + route
      })
    }   
  },

  /**
   * 组件的方法列表
   */ 
  methods: {
    OnScanBox:function(){
      const that = this; 
      wx.scanCode({
        scanType: ['qrCode'],
        success(res) {
          console.log(res);
          wx.removeStorageSync('first'); 
          let getUrl = res.result;
          if (getUrl.indexOf('promoteCode=') > -1){//扫码的是高校端的申领盒子码
            if (wx.getStorageSync('userInfo').hostel_id != null) {
              wx.showToast({
                title: '您已经申领过盒子了',
                icon: 'none'
              })
            } else {
              wx.reLaunch({
                url: '/pages/index/apply_box?q=' + encodeURIComponent(getUrl),
              })
            }      
            return false;
          }
          let index = getUrl.indexOf('boxId=');
          if (index > -1) {
            let box_id = getUrl.substring(index + 6, getUrl.length);
            var curPageArr = getCurrentPages();
            var page = curPageArr[curPageArr.length - 1];
            let userMsg = wx.getStorageSync('allUserMsg');


            //游客判断是否可以绑定盒子管理员
            if (userMsg.userinfo.hostel_id == 'null' || userMsg.userinfo.hostel_id == null) {
              that.bindBoxManager(box_id,page);
              return false;
            }

            if (curPageArr[0].route.indexOf('/index')>-1){//当前打开的是首页       
              if (userMsg == undefined || userMsg == '') {
                wx.login({
                  success: function (res) {
                    //发送请求
                    wx.request({
                      url: App.data.globalAPI + '/users/weixin/login', //接口地址
                      data: {
                        code: res.code,
                        source: 'small program',//注册来源标识
                        invite_id: ''//邀请人标识
                      },
                      header: {
                        'content-type': 'application/json' //默认值
                      },
                      success: function (res) {
                        if (res.data.error == 0) {
                          wx.setStorageSync('token', res.data.data.token);
                          wx.setStorageSync('userInfo', res.data.data.userinfo);
                          wx.setStorageSync('allUserMsg', res.data.data);

                          
                        }
                      }
                    })
                  }, fail(res) {
                    wx.showModal({
                      title: '提示',
                      content: '网络异常，请稍后重试！',
                      showCancel: false,
                      success(res) {

                      }
                    })
                  }
                })

              }else{
                that.getUserStatus(box_id, page);
              }
                     
            }else{
              wx.redirectTo({
                url: '/pages/index/index?boxId=' + box_id,
              })
            }

          }
          else {
            wx.showToast({
              title: '二维码错误',
              icon: 'none'
            })
          }

        }
      })
    },
    getUserStatus: function (box_id,page){
      let userMsg = wx.getStorageSync('allUserMsg');

      if (page.data.boxId != box_id) {//扫码盒子不是当前显示盒子
        if (userMsg.box.box_id == box_id) { //扫码的是自己宿舍
          page.setData({
            historyRecord: userMsg.first_supply.order_status != '3' ? false : true,
            boxManager: userMsg.userinfo.havebox == 1 ? true : false
          })

        } else {
          // page.setData({
          //   boxManager: true,
          //   historyRecord:((box_id != userMsg.box.box_id) && userMsg.hostel_box) ? true : false, //非本宿舍盒子如果有盒子就有记录，没盒子就无记录
          // })
          page.setData({
            historyRecord: ((box_id != userMsg.box.box_id) && userMsg.box.box_id != null) ? true : false,
            boxManager: true
          })
   
          if ((userMsg.first_supply.order_status == '0' || userMsg.first_supply.order_status == null) && userMsg.hostel_box==false) {
            page.setData({
              historyRecord: ((box_id != userMsg.box.box_id) && userMsg.box.box_id != null) ? true : false,
              boxManager: false
            })
          } else if (userMsg.first_supply.order_status == null && userMsg.box.box_id){//普通消费宿舍有盒子
            page.setData({
              historyRecord: ((box_id != userMsg.box.box_id) && userMsg.box.box_id != null) ? true : false,
              boxManager: true
            })
          }
          else if (userMsg.first_supply.order_status !='3') {//管理员盒子没送到
            page.setData({
              historyRecord: ((box_id != userMsg.box.box_id) && userMsg.box.box_id != null) ? true : false,
              boxManager: false
            })
          }
        }

        page.setData({
          boxBtnStatus: '前往消费',
          boxId: box_id,
          goodsList: [],

        })
        page.getBoxGoodsList();//消费列表的刷新
        page.getBoxAddress();//获取盒子地址
        page.clearShopCart(); //清空 购物车
      } 
    },

    // 我的
    goPersonCenter:function(){
      var curPageArr = getCurrentPages();
      var page = curPageArr[curPageArr.length - 1];//本页面
      wx.setStorageSync('boxId', page.data.boxId)
      wx.navigateTo({
        url: this.data.tabBar[4].pagePath,
      })
    },

    //绑定盒子管理员
    bindBoxManager: function (boxId, page){
      let that = this;
      wx.request({
        url: App.data.globalAPI + '/box/attr/getstatus', //接口地址
        data: {
          token: wx.getStorageSync('token'),
          box_id: boxId,
        },
        header: {
          'content-type': 'application/json' //默认值
        },
        success: function (res) {
          if (res.data.error == 0) {
            if (res.data.data.master == 0 && res.data.data.is_apply){ //没有管理员且可以申请盒子
              wx.redirectTo({
                url: '/pages/index/apply_box?boxId=' + boxId,
              })
            }else{
              var curPageArr = getCurrentPages();
              var page = curPageArr[curPageArr.length - 1];

              that.getUserStatus(boxId, page);
            }
          }else{
            wx.showToast({
              title: res.data.msg,
              icon:'none'
            })
          }
        }
      })
    }, 
    
    // 地址跳转
    goTabPage:function(e){
      let path = e.currentTarget.dataset.path;
      let index = e.currentTarget.dataset.index;
      if(index==1){ //喵趣
        path = App.data.globalUGC + '/?dev=1&token=' + wx.getStorageSync('token') + '&school_id=' + wx.getStorageSync('schoolId') + '&longitude=' + wx.getStorageSync('longitude') + '&latitude=' + wx.getStorageSync('latitude') + '&dev=1&openid=' + wx.getStorageSync('userInfo').openid;
      }else if(index==2){ //玩赚
        path = App.data.globalUGC + '/wanzhuan?token=' + wx.getStorageSync('token') + '&school_id=' + wx.getStorageSync('schoolId') + '&longitude=' + wx.getStorageSync('longitude') + '&latitude=' + wx.getStorageSync('latitude') + '&dev=1&openid=' + wx.getStorageSync('userInfo').openid;
      }
      
      if (this.data.current != path){
        if(index==1 || index ==2){
          wx.navigateTo({
            url: '/pages/apply/web_page?url=' + encodeURIComponent(path)
          })
        }else{
          wx.reLaunch({
            url: path,
          })
        }
      }
    }

  } 
})
